const db = require('../db/index')
const router = require('../router/article.js')
const path = require('path')

exports.getArticles = (req, res) =>{

		//此处用flag标志是主页发来的请求还是点击节点发来的，主页发来的要返回total
		if(req.query.flag==0)
			sql = `select * from ev_articles limit ${(req.query.page-1)*20+1},20`
		else
			sql = `select * from ev_articles where state <> '草稿'`
			
		//主页搜索时的，注意用 `${}`
		if(req.user != undefined)
		{	
			authorid = req.user.id
			state = req.query.state
			sql = `select * from ev_articles where author_id = '${authorid}' and state = '${state}'`
		}

		db.query(sql, (err,results)=>{
			if(err) return res.cc(err)
			if(results.length<=0) return res.cc('Failed')

			res.send({
				status: 0,
				message: '获取文章分类列表成功！',
				data: results,
			})
})}

exports.getDrafts = (req, res)=>{
	if(req.user != undefined)
	{	
		authorid = req.user.id
		sql = `select * from ev_drafts where author_id = '${authorid}'`	//不用""而用``则能向lookfor一样用${}表示变量了
		db.query(sql=>(err,results)=>{
			if(err) return res.cc(err)

			if(results.length<=0) return res.cc('Failed')
		
			res.send({
				status: 0,
				message: '获取文章分类列表成功！',
				data: results,
			})
			}
		)
	}
}

exports.getArticlesDetail = (req, res) =>{
	const sql = "select * from ev_articles where Id = ?"
			db.query(sql,req.params.id, (err,results)=>{
				if(err) return res.cc(err)
				if(results.length<=0) return res.cc('Failed')
				res.send({
					status: 0,
					message: '获取文章分类列表成功！',
					data: results,
				})
	})
}

exports.addArticle = (req, res) => {
	const articleInfo = {
	  ...req.body,
	  pub_date: new Date().Format("yyyy/MM/dd HH:mm"),
	  author_id: req.user.id,
	}
	const sql = `insert into ev_articles set ?`

	db.query(sql, articleInfo, (err, results) => {
		
	  if (err) return res.cc(err)

	  if (results.affectedRows !== 1) 
		return res.cc('发布文章失败！')

	  res.cc('发布文章成功', 0)
	})
}

exports.deleteArticle = (req, res) =>{
	const sql = 'delete from ev_articles where Id=?'
	// const sql = `update ev_articles set is_delete=1 where id=?`

	db.query(sql,req.query.Id, (err, results)=>{
		if(err)
			return res.cc(err)
			// console.log(results.affectedRows)
		if(results.affectedRows !== 1)
			return res.cc('删除失败!')
		
		res.cc('删除成功!' ,0)
	})
}

exports.correctArticle = (req, res)=>{
	
	// const articleInfo = {
	//   ...req.body,
	//   // cover_img: path.join('/uploads', req.file.filename),
	//   pub_date: new Date(),
	//   Id: req.params.Id
	// }这里用对象更新还不行，唉
	const sql = `update ev_articles set title = ?,content = ?,state = ?,pub_date = ?
		where Id = ?`
	db.query(sql,	[req.body.title,req.body.content,req.body.state,new Date(),req.params.Id], (err, results) => {

	  if (err) return res.cc(err)
	
	  if (results.affectedRows !== 1) 
		return res.cc('发布文章失败！')
	
	  res.cc('发布文章成功', 0)
	})
}